package com.example.nirvana.dataStructure;

/**
 * 链表
 */
public class MyLine {
    private LineNode head;

    public MyLine() {
        head = null;
    }

    /**
     * 添加节点
     *
     * @param key
     * @param value
     */
    public void addNode(int key, int value) {
        // 链表为空，直接将节点添加到head中
        if(head == null) {
            head = new LineNode(key, value);
        }else {
            LineNode current = head;
            // 查找链表尾部
            while(current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(new LineNode(key, value)); // 新节点的添加
        }
    }

    /**
     * 获取节点
     *
     * @param key
     * @return
     */
    private LineNode getNode(int key) {
        LineNode current = head;
        if(head.getKey() == key) {
            return head;
        }else {
            current = head.getNext();
            while(current.getKey() != key) {
                current = current.getNext();
            }
            return current;
        }
    }

    /**
     * 删除节点
     *
     * @param key
     * @return
     */
    public boolean delNode(int key) {
        LineNode current = head;
        LineNode parent;
        // 确定链表不为空，否则删除失败
        if(head == null) {
            return false;
        }else if(head.getKey() == key) {
            // 头节点比较特殊，需要特殊处理
            head = head.getNext();
            return true;
        }else {
            current = head.getNext();
            parent = head;
            // 查询待删除节点及其前继节点
            while(current.getKey() != key) {
                current = current.getNext();
                parent = parent.getNext();
            }
            // 如果查到待删除节点则删除，否则删除失败
            if(current != null) {
                parent.setNext(current.getNext());
                return true;
            }else {
                return false;
            }
        }
    }

    /**
     * 插入节点
     *
     * @param newNode
     * @param index
     * @return
     */
    public boolean insertNode(LineNode newNode, int index) {
        LineNode preNode = head;
        if(preNode == null || index == 0) {
            preNode = newNode;
            return true;
        }else {
            while(preNode.getNext() != null && index-- > 0) {
                preNode = preNode.getNext();
            }
            newNode.setNext(preNode.getNext());
            preNode.setNext(newNode);
            return true;
        }
    }
}
